package com.conversationboard.network;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.conversationboard.config.Configuration;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.User;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;

/**
 * Makes use of MaxMind GeoData, available at http://www.maxmind.com/
 * 
 * @author Keith Watson
 *
 */

public class UserLocation {

	private static LookupService lookupService;

	static {

		File file = new File(Configuration.getInstance().getGeoDatabasePath());

		if (!file.exists()) {
			Logger.log(new Date(), "Could not find location database file.", User.getSystemUser());
		}

		try {
			lookupService = new LookupService(Configuration.getInstance().getGeoDatabasePath(), LookupService.GEOIP_MEMORY_CACHE);
		} catch (IOException e) {
			Logger.log(new Date(), "Could not load location database: " + e.getMessage(), User.getSystemUser());
		}

	}


	public static String getLocation(String ipAddress) {

		if (ipAddress == null || ipAddress.trim().equals("") || lookupService == null) {
			return "";
		}

		Location location = lookupService.getLocation(ipAddress);

		if (location == null) {
			return "";
		}

		if (location.city == null) {
			return location.countryName;
		} else if (location.countryName == null) {
			return location.city;
		} else if ((location.countryName == null) && (location.city == null)) {
			return "";
		} else {
			return (location.city + ", " + location.countryName);
		}

	}

}
